<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>专家讲座 - 农业知识交流论坛</title>
  <link rel="stylesheet" th:href="@{/bootstrap/css/bootstrap.min.css}">
  <link rel="stylesheet" th:href="@{/layui/css/layui.css}">
  <link rel="stylesheet" th:href="@{/css/mycss.css}">
  <link rel="stylesheet" th:href="@{/zplayer/css/zplayer.min.css}">
  <script th:src="@{/zplayer/js/zplayer.min.js}"></script>
  <link rel="stylesheet" href="//at.alicdn.com/t/font_2080705_x7u3h1yrrfc.css">
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#2E7D32', // 主色调：绿色，代表农业
            secondary: '#F9A825', // 辅助色：橙色，代表活力
            neutral: {
              100: '#F5F7F3',
              200: '#E8EDE3',
              300: '#D4DCD0',
              400: '#AAB6A2',
              500: '#7F8D77',
              600: '#55614E',
              700: '#3A4236',
              800: '#21261E',
              900: '#141613',
            }
          },
          fontFamily: {
            sans: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }

      .text-shadow {
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }

      .transition-custom {
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      }

      .card-hover {
        @apply hover:shadow-lg hover:-translate-y-1 transition-all duration-300;
      }

      .btn-primary {
        @apply bg-primary hover:bg-primary/90 text-white font-medium py-2 px-4 rounded-lg transition-all duration-300;
      }

      .btn-secondary {
        @apply bg-secondary hover:bg-secondary/90 text-white font-medium py-2 px-4 rounded-lg transition-all duration-300;
      }

      .btn-outline {
        @apply border border-primary text-primary hover:bg-primary/10 font-medium py-2 px-4 rounded-lg transition-all duration-300;
      }

      .btn-outline-secondary {
        @apply border border-secondary text-secondary hover:bg-secondary/10 font-medium py-2 px-4 rounded-lg transition-all duration-300;
      }

      .btn-outline-danger {
        @apply border border-red-500 text-red-500 hover:bg-red-500 hover:text-white font-medium py-2 px-4 rounded-lg transition-all duration-300;
      }
    }
  </style>
</head>
<body>

<!-- 导航栏 -->
<nav class="bg-white shadow-md">
  <div class="container mx-auto px-4">
    <div class="flex justify-between items-center h-16">
      <div class="flex items-center">
        <a href="/" class="text-xl font-bold text-primary">农业知识交流论坛</a>
      </div>
      <div class="flex items-center space-x-8">
        <a href="/" class="text-gray-600 hover:text-primary transition-colors">首页</a>
        <a href="/discover" class="text-gray-600 hover:text-primary transition-colors">发现</a>
        <a href="/lecture" class="text-primary font-medium">专家讲座</a>
      </div>
    </div>
  </div>
</nav>

<div class="container mx-auto px-4">
  <!-- 专题讲座页面 -->
  <section class="mb-12">
    <div class="flex justify-between items-center mb-6">
      <h2 class="text-2xl font-bold flex items-center">
        <i class="fa-solid fa-calendar-check text-primary mr-2"></i>
        专家讲座
      </h2>
      <button id="publish-lecture-btn" class="btn-secondary flex items-center">
        <i class="fa-solid fa-plus mr-2"></i>
        发布讲座
      </button>
    </div>

    <!-- 讲座筛选 -->
    <div class="bg-white rounded-xl p-4 shadow-md mb-6">
      <div class="flex flex-wrap gap-4">
        <div class="relative">
          <select id="category-filter" class="pl-4 pr-10 py-2 rounded-lg border border-neutral-300 focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary transition-all">
            <option value="">所有分类</option>
            <option value="planting">种植技术</option>
            <option value="breeding">养殖技术</option>
            <option value="processing">农产品加工</option>
            <option value="policy">农业政策</option>
          </select>
          <i class="fa-solid fa-chevron-down absolute right-3 top-1/2 -translate-y-1/2 text-neutral-400 pointer-events-none"></i>
        </div>

        <div class="relative flex-grow max-w-md flex">
          <input type="text" id="search-input" placeholder="搜索讲座..."
                 class="w-full pl-10 pr-4 py-2 rounded-l-lg border border-neutral-300 focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary transition-all">
          <button id="search-button" class="px-4 py-2 bg-primary text-white rounded-r-lg hover:bg-primary/90 transition-colors flex items-center gap-1">
            <i class="fa-solid fa-search"></i>
            <span>搜索</span>
          </button>
        </div>
      </div>
    </div>

    <!-- 讲座列表 -->
    <div id="lecture-list" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
      <!-- 讲座卡片将通过JavaScript动态添加 -->
        <div class="bg-white rounded-xl overflow-hidden shadow-md card-hover" th:each="lecture : ${lectures}">
          <div class="relative h-48">
            <img src="https://picsum.photos/600/400?random=${lecture.id}" alt="讲座图片" class="w-full h-full object-cover">
            <div class="absolute top-3 left-3 bg-${lecture.category == 'planting' || lecture.category == 'processing' || lecture.category == 'policy' ? 'primary' : 'secondary'}/90 text-white text-xs font-medium px-2 py-1 rounded" th:text="${lecture.category == 'planting' ? '种植技术' : lecture.category == 'breeding' ? '养殖技术' : lecture.category == 'processing' ? '农产品加工' : '农业政策'}"></div>
            <div class="absolute top-3 right-3 bg-secondary/90 text-white text-xs font-medium px-2 py-1 rounded flex items-center">
              <i class="fa-solid fa-clock mr-1"></i> <span th:text="${#dates.format(lecture.time, 'yyyy-MM-dd HH:mm')}"></span>
            </div>
          </div>
          <div class="p-4">
            <h3 class="text-lg font-semibold mb-2" th:text="${lecture.title}"></h3>
            <p class="text-gray-600 text-sm mb-4" th:text="${lecture.description}"></p>
            <div class="flex justify-between items-center">
              <div class="flex items-center text-sm text-gray-500">
                <i class="fa-solid fa-map-marker-alt mr-1"></i>
                <span th:text="${lecture.location}"></span>
              </div>
              <div class="flex items-center text-sm text-gray-500">
                <i class="fa-solid fa-user mr-1"></i>
                <span th:text="${lecture.nickname}"></span>
              </div>
            </div>
            <div class="mt-4 flex justify-between items-center">
              <button class="btn-primary flex items-center" th:onclick="'bookLecture(' + ${lecture.id} + ')'">
                <i class="fa-solid fa-calendar-check mr-2"></i>
                预约讲座
              </button>
              <div class="flex items-center text-sm text-gray-500">
                <i class="fa-solid fa-users mr-1"></i>
                <span th:text="${lecture.attendeeCount} + '人已预约'"></span>
              </div>
            </div>
            <!-- 删除按钮 -->
            <div class="mt-4" th:if="${session.loginUser.roleId == 1 || (session.loginUser.roleId == 3 && lecture.publisherUid == session.loginUser.uid)}">
              <button class="btn btn-danger btn-sm" th:onclick="'deleteLecture(' + ${lecture.id} + ')'">删除</button>
            </div>
          </div>
        </div>

    </div>
  </section>
</div>

<!-- 发布讲座模态框 -->
<div id="publish-modal" class="fixed inset-0 bg-gray-500 bg-opacity-75 hidden justify-center items-center z-50">
  <div class="bg-white p-8 rounded-lg shadow-lg w-96">
    <h2 class="text-2xl font-bold mb-4">发布讲座</h2>
    <form id="publish-form">
      <div class="mb-4">
        <label for="lecture-title" class="block text-sm font-medium text-gray-700">讲座标题</label>
        <input type="text" id="lecture-title" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm">
      </div>
      <div class="mb-4">
        <label for="lecture-category" class="block text-sm font-medium text-gray-700">讲座分类</label>
        <select id="lecture-category" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm">
          <option value="planting">种植技术</option>
          <option value="breeding">养殖技术</option>
          <option value="processing">农产品加工</option>
          <option value="policy">农业政策</option>
        </select>
      </div>
      <div class="mb-4">
        <label for="lecture-time" class="block text-sm font-medium text-gray-700">讲座时间</label>
        <input type="datetime-local" 
               id="lecture-time" 
               class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm"
               required>
      </div>
      <div class="mb-4">
        <label for="lecture-location" class="block text-sm font-medium text-gray-700">讲座地点</label>
        <input type="text" id="lecture-location" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm">
      </div>
      <div class="mb-4">
        <label for="lecture-description" class="block text-sm font-medium text-gray-700">讲座描述</label>
        <textarea id="lecture-description" rows="4" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm"></textarea>
      </div>
      <div class="flex justify-end">
        <button type="button" id="cancel-publish" class="btn-outline mr-2">取消</button>
        <button type="submit" class="btn-primary">发布</button>
      </div>
    </form>
  </div>
</div>

<div th:replace="~{common/footer::footer}"></div>

<a class="to-top"><i class="iconfont icon-fanhuidingbu1" style="font-size:50px;color: #007bff"></i></a>
<script th:src="@{/js/jquery-3.5.1.min.js}"></script>
<script th:src="@{/bootstrap/js/bootstrap.bundle.min.js}"></script>
<script th:src="@{/js/toTop.js}"></script>
<script th:src="@{/layui/layui.all.js}"></script>

<script>
  document.addEventListener('DOMContentLoaded', function () {
    const publishBtn = document.getElementById('publish-lecture-btn');
    const publishModal = document.getElementById('publish-modal');
    const cancelPublish = document.getElementById('cancel-publish');
    const publishForm = document.getElementById('publish-form');
    const lectureList = document.getElementById('lecture-list');
    const timeInput = document.getElementById('lecture-time');

    // 设置时间输入框的最小值为当前时间
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const minDateTime = `${year}-${month}-${day}T${hours}:${minutes}`;
    timeInput.min = minDateTime;

    // 显示发布讲座模态框
    publishBtn.addEventListener('click', function () {
      publishModal.classList.remove('hidden');
    });

    // 隐藏发布讲座模态框
    cancelPublish.addEventListener('click', function () {
      publishModal.classList.add('hidden');
    });

    // 处理发布讲座表单提交
    publishForm.addEventListener('submit', function (e) {
      e.preventDefault();
      const title = document.getElementById('lecture-title').value;
      const category = document.getElementById('lecture-category').value;
      const time = document.getElementById('lecture-time').value;
      const location = document.getElementById('lecture-location').value;
      const description = document.getElementById('lecture-description').value;

      // 验证表单数据
      if (!title || !category || !time || !location || !description) {
        alert('请填写所有必填字段');
        return;
      }

      // 发送POST请求到服务器
      fetch('/lecture/add', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams({
          'title': title,
          'category': category,
          'time': time,
          'location': location,
          'description': description
        })
      })
      .then(response => {
        if (response.redirected) {
          window.location.href = response.url;
        } else if (response.ok) {
          window.location.reload();
        } else {
          throw new Error('发布失败');
        }
      })
      .catch(error => {
        console.error('发布失败:', error);
        alert('发布失败，请重试');
      });
    });

    // 处理讲座预约
    window.bookLecture = function(id) {
      fetch(`/lecture/book/${id}`, {
        method: 'POST'
      })
      .then(response => response.text())
      .then(result => {
        if (result === 'success') {
          alert('预约成功');
          window.location.reload();
        } else {
          alert(result || '预约失败');
        }
      })
      .catch(error => {
        console.error('预约失败:', error);
        alert('预约失败，请稍后重试');
      });
    };

    // 处理删除讲座
    window.deleteLecture = function(id) {
      if (confirm('确定要删除这个讲座吗？')) {
        fetch('/lecture/delete/' + id, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          }
        })
        .then(response => response.text())
        .then(result => {
          if (result === 'success') {
            alert('删除成功');
            window.location.reload();
          } else {
            alert(result || '删除失败');
          }
        })
        .catch(error => {
          console.error('Error:', error);
          alert('删除失败');
        });
      }
    };

    // 添加分类筛选功能
    const categoryFilter = document.getElementById('category-filter');
    categoryFilter.addEventListener('change', function() {
      const selectedCategory = this.value;
      window.location.href = `/lecture${selectedCategory ? '?category=' + selectedCategory : ''}`;
    });

    // 获取URL参数
    const urlParams = new URLSearchParams(window.location.search);
    
    // 设置当前选中的分类
    const categoryParam = urlParams.get('category');
    if (categoryParam) {
      categoryFilter.value = categoryParam;
    }

    // 添加搜索功能
    const searchInput = document.getElementById('search-input');
    const searchButton = document.getElementById('search-button');

    // 设置搜索框的初始值
    const searchTitleParam = urlParams.get('searchTitle');
    if (searchTitleParam) {
      searchInput.value = searchTitleParam;
    }

    // 搜索函数
    function performSearch() {
      const searchValue = searchInput.value.trim();
      const currentUrl = new URL(window.location.href);
      
      if (searchValue) {
        currentUrl.searchParams.set('searchTitle', searchValue);
      } else {
        currentUrl.searchParams.delete('searchTitle');
      }
      
      // 保留分类参数
      if (categoryParam) {
        currentUrl.searchParams.set('category', categoryParam);
      }
      
      window.location.href = currentUrl.toString();
    }

    // 点击搜索按钮触发搜索
    searchButton.addEventListener('click', performSearch);

    // 按回车键触发搜索
    searchInput.addEventListener('keypress', function(e) {
      if (e.key === 'Enter') {
        performSearch();
      }
    });
  });
</script>

<script>
  document.addEventListener('DOMContentLoaded', function () {
    const publishBtn = document.getElementById('publish-lecture-btn');
    const publishModal = document.getElementById('publish-modal');
    const cancelPublish = document.getElementById('cancel-publish');
    const publishForm = document.getElementById('publish-form');
    const lectureList = document.getElementById('lecture-list');

    // 显示发布讲座模态框
    publishBtn.addEventListener('click', function () {
      publishModal.classList.remove('hidden');
    });

    // 隐藏发布讲座模态框
    cancelPublish.addEventListener('click', function () {
      publishModal.classList.add('hidden');
    });

    // 处理发布讲座表单提交
    publishForm.addEventListener('submit', function (e) {
      e.preventDefault();
      const title = document.getElementById('lecture-title').value;
      const category = document.getElementById('lecture-category').value;
      const time = document.getElementById('lecture-time').value;
      const location = document.getElementById('lecture-location').value;
      const description = document.getElementById('lecture-description').value;

      // 创建新的讲座卡片
      const newLectureCard = document.createElement('div');
      newLectureCard.className = 'bg-white rounded-xl overflow-hidden shadow-md card-hover';
      newLectureCard.innerHTML = `
                <div class="relative h-48">
                    <img src="https://picsum.photos/600/400?random=${Math.floor(Math.random() * 100)}" alt="讲座图片" class="w-full h-full object-cover">
                    <div class="absolute top-3 left-3 bg-${category === 'planting' || category === 'processing' || category === 'policy' ? 'primary' : 'secondary'}/90 text-white text-xs font-medium px-2 py-1 rounded">${category === 'planting' ? '种植技术' : category === 'breeding' ? '养殖技术' : category === 'processing' ? '农产品加工' : '农业政策'}</div>
                    <div class="absolute top-3 right-3 bg-secondary/90 text-white text-xs font-medium px-2 py-1 rounded flex items-center">
                        <i class="fa-solid fa-clock mr-1"></i> ${new Date(time).toLocaleString()}
                    </div>
                </div>
                <div class="p-5">
                    <h3 class="font-semibold text-lg mb-2">${title}</h3>
                    <div class="flex items-center mb-3">
                        <img src="https://picsum.photos/32/32?random=${Math.floor(Math.random() * 100)}" alt="专家头像" class="w-8 h-8 rounded-full object-cover mr-2">
                        <span class="text-sm font-medium">未知专家</span>
                        <span class="ml-auto flex items-center text-neutral-500 text-sm">
                            <i class="fa-solid fa-users mr-1"></i> <span class="attendee-count">0</span>人已预约
                        </span>
                    </div>
                    <p class="text-neutral-600 text-sm mb-4 line-clamp-2">${description}</p>
                    <div class="flex items-center justify-between">
                        <div class="flex items-center space-x-2">
                            <button class="btn-outline-secondary text-sm py-1.5 book-lecture-btn" data-id="${Date.now()}">
                                预约讲座
                            </button>
                            <th:block th:if="${lecture.nickname == session.userInfo.nickname}">
                                <button class="btn-outline-danger text-sm py-1.5 delete-lecture-btn" data-id="${Date.now()}">
                                    删除讲座
                                </button>
                            </th:block>
                        </div>
                        <span class="text-neutral-500 text-xs">${location}</span>
                    </div>
                </div>
            `;

      // 添加新的讲座卡片到列表
      lectureList.appendChild(newLectureCard);

      // 隐藏模态框并清空表单
      publishModal.classList.add('hidden');
      publishForm.reset();
    });

    // 处理讲座预约
    lectureList.addEventListener('click', function (e) {
      if (e.target.classList.contains('book-lecture-btn')) {
        const button = e.target;
        const lectureId = button.dataset.id;
        
        // 禁用按钮，防止重复点击
        button.disabled = true;
        button.textContent = '预约中...';
        
        fetch(`/lecture/book/${lectureId}`, {
          method: 'POST'
        })
        .then(response => response.text())
        .then(result => {
          if (result === 'success') {
            const attendeeCountElement = button.closest('.card-hover').querySelector('.attendee-count');
            let attendeeCount = parseInt(attendeeCountElement.textContent);
            attendeeCount++;
            attendeeCountElement.textContent = attendeeCount;
            button.textContent = '已预约';
            button.classList.remove('btn-outline-secondary');
            button.classList.add('btn-secondary');
          } else {
            button.disabled = false;
            button.textContent = '预约讲座';
            alert(result);
          }
        })
        .catch(error => {
          console.error('预约失败:', error);
          button.disabled = false;
          button.textContent = '预约讲座';
          alert('预约失败，请稍后重试');
        });
      }
    });
  });
</script>
<script>
  document.getElementById('lecture-button').addEventListener('click', function() {
    window.location.href = 'lecture.html';
  });
</script>

<script>
// 删除讲座
function deleteLecture(id) {
    if (confirm('确定要删除这个讲座吗？')) {
        fetch('/lecture/delete/' + id, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .then(response => response.text())
        .then(result => {
            if (result === 'success') {
                alert('删除成功');
                window.location.reload();
            } else {
                alert(result || '删除失败');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('删除失败');
        });
    }
}
</script>
</body>
</html>